package com.example.tobebigfe.jsbridge

import android.app.Activity.RESULT_CANCELED
import android.app.Activity.RESULT_OK
import android.webkit.WebView
import org.json.JSONObject
import android.provider.MediaStore
import android.content.Intent
import android.graphics.Bitmap
import android.webkit.MimeTypeMap
import java.io.File
import java.io.FileOutputStream


class JSBridgeCamera(val activity: WebActivity, webView: WebView) : BridgeModuleBase(webView) {

    private val REQ_CODE = 200
    private val appCacheDir = File(activity.cacheDir, activity.application.packageName)
    private val cameraCacheDir = File(appCacheDir, "Camera")

    init {
        if (!(cameraCacheDir.exists() && cameraCacheDir.isDirectory)) {
            cameraCacheDir.mkdirs()
        }
    }

    override fun callFunc(func: String, callbackId: String, arg: JSONObject) {
        when (func) {
            "takePicture" -> takePicture(callbackId, arg)
            "takeVideo" -> takeVideo(callbackId, arg)
        }
    }

    private fun takePicture(callbackId: String, arg: JSONObject) {
        // 创建去相机的意图(Intent), ACTION_IMAGE_CAPTURE（拍照）
        val takePhotoIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        // 检查系统是否支持相机
        if (takePhotoIntent.resolveActivity(activity.packageManager) == null) {
            // 不支持返回不成功
            val json = JSONObject()
            json.put("success", false)
            json.put("error", "This device is not support camera.")
            callback(callbackId, json)
        } else {
            // 调用前面定义的callback方式打开摄像机
            activity.startActivityForCallback(takePhotoIntent, REQ_CODE) { requestCode: Int, resultCode: Int, result: Intent? ->
                // 不是对应的requestCode
                if (REQ_CODE != requestCode) {
                    return@startActivityForCallback false
                }


                val json = JSONObject()

                if (resultCode == RESULT_OK) {
                    // 获取录制的视频路径
                    val bitmap = result?.extras?.get("data") as Bitmap
                    // 使用时间戳创建一个文件
                    val cacheFile = File(cameraCacheDir, "takePicture_${System.currentTimeMillis()}.jpg")
                    // 下面是将图片写入文件
                    var fos: FileOutputStream? = null
                    try {
                        fos = FileOutputStream(cacheFile)
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                    } catch (error: Throwable) {
                        json.put("success", false)
                        json.put("error", error.localizedMessage)
                        return@startActivityForCallback true
                    } finally {
                        fos?.close()
                    }
                    json.put("success", true)
                    json.put("file", "file://${cacheFile.absolutePath}")
                    json.put("type", MimeTypeMap.getSingleton().getMimeTypeFromExtension(cacheFile.absolutePath))
                } else {
                    json.put("success", false)
                    json.put("canceled", resultCode == RESULT_CANCELED)
                    json.put("error", "Result code is $resultCode")
                }

                callback(callbackId, json)
                true
            }
        }
    }

    private fun takeVideo(callbackId: String, arg: JSONObject) {
        // 创建去相机的意图(Intent)，ACTION_VIDEO_CAPTURE（拍视频）
        val takePhotoIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
        // 检查系统是否支持相机
        if (takePhotoIntent.resolveActivity(activity.packageManager) == null) {
            // 不支持返回不成功
            val json = JSONObject()
            json.put("success", false)
            json.put("error", "This device is not support camera.")
            callback(callbackId, json)
        } else {
            // 调用前面定义的callback方式打开摄像机
            activity.startActivityForCallback(takePhotoIntent, REQ_CODE) { requestCode: Int, resultCode: Int, result: Intent? ->
                // 不是对应的requestCode
                if (REQ_CODE != requestCode) {
                    return@startActivityForCallback false
                }


                val json = JSONObject()

                if (resultCode == RESULT_OK) {
                    // 获取视频地址，这里是和takePicture不同的地方
                    val videoUri = result!!.data!!
                    val mimeType = activity.contentResolver.getType(videoUri)
                    json.put("success", true)
                    json.put("type", mimeType)
                    json.put("file", videoUri.toString())

                } else {
                    json.put("success", false)
                    json.put("canceled", resultCode == RESULT_CANCELED)
                    json.put("error", "Result code is $resultCode")
                }

                callback(callbackId, json)
                true
            }
        }
    }
}